<template>
    <div @mousedown="dragdown($event)" @mouseup="dragup($event)" @mousemove="dragmove($event)" id="chatBox">
        <div id="remind" v-if="">
                有新消息
        </div>
        <div class="wrapper chat">
            <div class="container">
                <div class="left">
                    <div class="top">
                        <input type="text" placeholder="Search" />
                        <a href="javascript:;" class="search"></a>
                    </div>
                        <ul class="people" style="height: 500px; overflow-y: scroll; overflow-x: hidden">
                                <li :zai="frind.state" @click="setToId(frind.id, i)" v-for="(frind, i) in friends" class="person" data-chat="person1">
                                    <img :src="frind.imgUrl" alt="" />
                                    <span class="name" style="display: inline-block">{{frind.nickName}}</span>
                                    <i v-if="frind.state==2" style="margin-left: 10px; color: #62b038; " class="el-icon-circle-check"><span >在线</span></i>
                                    <i v-if="frind.state==1" style="margin-left: 10px;  color: #a8afb1; padding-right: 3px" class="el-icon-circle-close"><span>离线</span></i>
                                    <span class="time">2:09 PM</span>
                                    <span class="preview">I was wondering...</span>
                                    <span class="weidu" :id="frind.id">这里是新消息提醒</span>
                                </li>
                             </ul>
                </div>
                <div class="right">
                    <div class="top" style="user-select: none"><span><span class="name" id="chat_friend_name"></span></span>
                        <svg @click="showChatS"  t="1609900796121" class="icon delect" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3517" width="200" height="200"><path d="M240.896 240.896a21.333333 21.333333 0 0 1 27.221333-2.432l2.986667 2.432 512 512a21.333333 21.333333 0 0 1-27.221333 32.64l-2.986667-2.432-512-512a21.333333 21.333333 0 0 1 0-30.208z" fill="#333333" p-id="3518"></path><path d="M752.896 240.896a21.333333 21.333333 0 0 1 32.64 27.221333l-2.432 2.986667-512 512a21.333333 21.333333 0 0 1-32.64-27.221333l2.432-2.986667 512-512z" fill="#333333" p-id="3519"></path></svg></div>
                    <div id="msgFa" class="chat" data-chat="text" style="display: inline-block; overflow:auto">
                        <k>
                            <div class="conversation-start" style="user-select: none">
                                <span>{{date+"-"+date2+"时"+date3+"分"}}</span>
                            </div>
                        </k>
<!--                        <div :class="l.per"  v-for="l in leave" v-html="l.msg">-->
<!--                        </div>-->
                    </div>

                    <div class="write">
                        <a href="javascript:;" class="write-link attach"></a>
                        <input v-model="msg" type="text" @keydown.enter="send" id="inputMsg" />
                        <a href="javascript:;" class="write-link smiley"  @click="showEmoj(1)"></a>
                        <a href="javascript:;" class="write-link send" @click="send" ></a>
                    </div>
                    <div class="emoj" id="emoj">
                        <img v-for="i in 75" @click="emojClick(i)" :src="geturl(i)" alt="">
                    </div>
                </div>
            </div>
        </div>

    </div>
</template>

<script>


    import constant from "../../utils/constant";

    let maxNum = 0;

    var websocket = null;
    const myId = parseInt(sessionStorage.getItem("userId"));
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        let id = sessionStorage.getItem("userId") + '';
        //连接WebSocket节点
        //let ur = "ws://localhost:83/connectWebSocket/"+id;
        let ur = constant.webSocketUrl+id;
        //  alert(ur);
        websocket = new WebSocket(ur);
    }
    else{
        alert('Not support websocket')
    }


    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };


    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    let msgNum = new Array();
    let maxCnt = 0;
    var Ncnt = 0;
    let fromuserId = 0;
    let sendToId = 0;
    //接收到消息的回调方法
    websocket.onmessage = function(event){
        if(Ncnt != 0)
            document.getElementById("remind").style.display = "block";
      //  console.log(event);
        let msg = event.data;
        var obj = eval('(' + msg + ')');
        let s = obj.textMessage;
        //得到新消息来源的用户id 然后将对应的用户添加一个新消息提醒
        fromuserId = obj.fromuserId;
        if(s != undefined){
            msgNum[fromuserId]++;
            for (let i = 0; i <= maxCnt; i++){
                if(msgNum[i] != undefined && msgNum[i] != 0){
                    document.getElementById(fromuserId).style.display = "inline-block";
                    document.getElementById(fromuserId).innerText = msgNum[i];
                }
            }
            Ncnt++;
            if(Ncnt != 0)
                document.getElementById("remind").style.display = "block";

            setMessageInnerHTML(s);
        }

    }


    //连接关闭的回调方法

    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }


    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }


    //console.log(document.getElementById("setMsg2").value);

    //将消息显示在网页上

    function setMessageInnerHTML(innerHTML){

        //alert(chat.leave);
        if(innerHTML != "close" && innerHTML != "open"){
            let t = {
                msg:innerHTML,
                per:'bubble you'
            };
            app.data().leave.push(t);
            //app.methods.setMsg();
            //location.reload();
            let Div = document.createElement("div");
            Div.setAttribute("class", "bubble you");
           // console.log(sendToId + "============");
            if(fromuserId == sendToId){
                let s = getEmojiUrl(innerHTML);
             //   console.log(s);
                Div.innerHTML = s;
                document.getElementById("msgFa").appendChild(Div);
            }

            let height = document.getElementById("msgFa").scrollHeight;
            document.getElementById("msgFa").scrollTop = height;

        }
    }


    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }


    //字符串匹配 把表情包编号转变成Img标签加文字
    function getEmojiUrl(t) {
        let s = '';
        for(let i = 0; i < t.length; i++){
            if(t[i] == 'e' && t[i + 1] == 'm' && t[i + 2] == 'o' && t[i + 3] == 'j' && t[i + 4] == '_' && (t[i + 5] > '0'&& t[i + 5] <= '9')){
                let index = parseInt(t[i + 5]);
                if(t[i + 6] >= '0' && t[i + 6] <= '9'){
                    index *= 10;
                    index += parseInt(t[i + 6]);
                    i += 6;
                }
                else{
                    i += 5;
                }
                // console.log(index);
                let url ="http://handsomehuang.cn:8081/arclist/"+index+".gif";
                let tt = `  <img height="25px" width="25px" class="emojMsg" src="`+url+`" >`;
                s += tt;

            }else{
                s += t[i];
            }
        }
        return s;
    }

    //发送消息
    // function send(){
    //     var message = document.getElementById('text').value;
    //     message = message+"#"+"001"+"#"+"002";
    //     websocket.send(message);
    // }


    import {request} from '../../network/request'
    //自定义组件名
    // 引入css

   // import emoj from "./emoj";
    setTimeout(function () {
        let height = document.getElementById("msgFa").scrollHeight;
        document.getElementById("msgFa").scrollTop = height;
    }, 2000)


    let nCnt = 0;
    let app = {
        name: "chat",
        data(){
            return{
                msg:'',
                friends:[],
                leave:[],
                to:0,
                date: new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + new Date().getDate() + " ",
                date2: new Date().getHours(),
                date3: new Date().getMinutes(),
                show_chat: 1,
                x:1200,
                y:100,
                fx:0,
                fy:0,
                move:0,
                show: 0
            }
        },
        methods:{
            showEmoj(){
                if(this.show == 1)
                 document.getElementById("emoj").style.display = "none";
                else
                    document.getElementById("emoj").style.display = "block";
                this.show ^= 1;
            },
            geturl(i){
                return "http://handsomehuang.cn:8081/arclist/"+i+".gif";
            },
            emojClick(i){
                this.msg += "emoj_"+i;
                this.showEmoj();
            },
            dragdown(e){
                this.fx = e.x;
                this.fy = e.y;
                document.getElementsByClassName("chat")[0].style.transition = "0s";
                this.move ^= 1;
                //console.log(this.move);
            },
            dragup(e){
                this.move =  this.move ^ 1;
              //  console.log(this.move);
                document.getElementsByClassName("chat")[0].style.transition = "0.5s";
                var x = e.x - this.fx;
                var y = e.y - this.fy;
                x = this.x + x;
                y = this.y + y;
                this.x = x;
                this.y = y;
            },
            dragmove(e){
               if(this.move == 1){

                   var x = e.x - this.fx;
                   var y = e.y - this.fy;
                   x = this.x + x;
                   y = this.y + y;
                   document.getElementsByClassName("chat")[0].style.left = x + "px";
                   document.getElementsByClassName("chat")[0].style.top = y + "px";

               }

            },
            send(){
                //console.log(this.msg);
                 this.setScroller();
                // alert(this.to);

                let s = getEmojiUrl(this.msg);

                let Div = document.createElement("div");
                Div.setAttribute("class", "bubble me");
                Div.setAttribute("id", "chatMsg" + (++maxNum));
                Div.innerHTML = s;
                document.getElementById("msgFa").appendChild(Div);
                console.log(document.getElementById("msgFa"));
                let height = document.getElementById("msgFa").scrollHeight;
                document.getElementById("msgFa").scrollTop = height;

                let id = sessionStorage.getItem("userId") + '';
                let message = this.msg+"#"+id+"#"+this.to;
                //alert(message);
                websocket.send(message);

                let t = this.msg;
               // console.log(t);
                s = getEmojiUrl(t);
                request({
                    url:"/insertMsg",
                    method: "post",
                    params:{
                        me:myId,
                        you:this.to,
                        msg:s,
                        time:this.date+this.date2+":"+this.date3
                    }
                }).then(res=>{
                 //   console.log(res.data);
                    //alert(res.data);

                }).catch(err=>{
                    //alert(err);
                    console.log(err);
                });
                this.msg = "";
            },
            setNone(){
                Ncnt = 0;
                document.getElementById("remind").style.display = "none";
            },
            sendMsgToFather(){
               // console.log(this);
                // alert("传送");
                //  this.$emit('getCnt',this.cnt);
               // this.$router.replace("/login");
            },
            setToId(id, i){
                let fa = document.getElementById("msgFa");
                for(let k = 0; k < maxNum; k++){
                    let t = document.getElementById("chatMsg" + k);
                    if(t != null)
                    fa.removeChild(t);
                }
                //让输入矿可以再次编辑
                document.getElementById("inputMsg").removeAttribute("disabled");
                this.leave = [];
                // alert(id);
                // this.leave = '';
                this.to = id;
                sendToId = id;
                var item = document.getElementsByClassName("person");
                // console.log(item);
                //点击用户以后 新的消息提醒清除
                document.getElementById(this.to).style.display = "none";
                msgNum[this.to] = 0;
                for(let k = 0; k < item.length; k++){
                    item[k].classList.remove("active");
                }
                item[i].classList.add("active");
                let name = item[i].children[1].innerText;
                // alert(name);
                document.getElementById("chat_friend_name").innerText = name;
                request({
                    url:"/getChatMsg",
                    method: "post",
                    params:{
                        me:myId,
                        you:id
                    }
                }).then(res=>{
                    console.log(res.data);
                    let data = res.data;
                    for(let i = 0; i < data.length; i++){
                        let who = "bubble you";
                        if(data[i].sendId == myId){
                            who = "bubble me"
                        }
                        this.leave.push({
                            msg:data[i].msg,
                            per:who
                        });
                        let Div = document.createElement("div");
                        Div.setAttribute("class", who);
                        Div.setAttribute("id", "chatMsg" + i);
                        Div.innerHTML = data[i].msg;
                        document.getElementById("msgFa").appendChild(Div);
                        console.log(document.getElementById("msgFa"));
                        let height = document.getElementById("msgFa").scrollHeight;
                        document.getElementById("msgFa").scrollTop = height;
                    }
                    maxNum = data.length;
                   // this.setScroller();
                }).catch(err=>{
                    console.log(err);
                });
            },
            showChatS(){
                //alert();
                this.setNone();
                //让Input标签不能编辑
                document.getElementById("inputMsg").setAttribute("disabled", "disabled");
                if( this.show_chat){
                    document.getElementsByClassName("chat")[0].style.left = "1000px";
                    document.getElementsByClassName("chat")[0].style.top = "100px";
                    document.getElementsByClassName("chat")[0].style.opacity=1;
                    this.x = 1000;
                    this.y = 100;
                    console.log(msgNum[3]);
                    this.setNewMsgRemid();
                }
                else{
                    document.getElementsByClassName("chat")[0].style.opacity=0;
                    document.getElementsByClassName("chat")[0].style.left = "-2000px";
                }

                this.show_chat ^= 1;
            },
            setScroller(){

                    let t = document.getElementById("msgFa");
                    let height = t.scrollHeight;
                    t.scrollTop = height;



            },
            setNewMsgRemid(){
                //设置好友给你发的新消息提醒
                    for (let i = 0; i <= msgNum.length; i++){
                        console.log(msgNum[i]);
                        if(msgNum[i] != undefined && msgNum[i] != 0){
                            document.getElementById(i).style.display = "inline-block";
                            document.getElementById(i).innerText = msgNum[i];
                        }
                    }


            }

        },
        created() {
            //alert();

            let id = sessionStorage.getItem("userId");
            id = parseInt(id);
            request({
                url:"/getAllUser",
                method: "post",
                params:{
                    id: id
                }
            }).then(res=>{
                console.log(res.data);
                this.friends = res.data;
                // for(let i = 0; i < res.data.length; i++){
                //     msgNum[res.data[i].id] = 0
                //
                //     if(res.data[i].id > maxCnt){
                //         maxCnt = res.data[i].id;
                //         //console.log(maxCnt);
                //     }
                // }
               // console.log(maxCnt);

            }).catch(err=>{
                console.log(err);
            });


            //alert();

        },
        mounted(){
            request({
                url:"/searchMsg",
                method: "post",
                params:{
                    id: myId
                }
            }).then(res=>{
                //alert();
                console.log(res.data);
                console.log("------");
                if(res.data.length != 0){
                    for(let i = 0; i < res.data.length; i++){
                        let you = res.data[i].sendId;
                        if(msgNum[you] != undefined){
                            msgNum[you]++;
                        }
                        else{
                            msgNum[you] = 1;
                        }
                     //   console.log(msgNum[4]);
                    }
                    document.getElementById("remind").style.display = "block";
                    this.setNewMsgRemid();
                }
            }).catch(err=>{
                console.log(err);
            });
        },
        components:{

        }


    }
    export default app

</script>

<style scoped>


    .emoj{
        position: absolute;
        width: 400px;
        height: 200px;
        z-index: 100;
        background-color: #dcdfe6;
        right: 30px;
        bottom: 70px;

    }
    #emoj{
        display: none;
    }
    .emoj img{
        height: 28px;
    }
    #remind{
        position: fixed;
        z-index: 100;
        right: 40px;
        bottom: 310px;

    }

    .delect{
        width: 40px;
        height: 40px;
        position: absolute;
        right: 5px;
        top: 5px;
        cursor: pointer;
    }
    .delect:hover{
        background-color: #fc5531;
    }
    .person i span{
        margin-left: 5px;
        font-size: 13px;
        line-height: 15px;
    }
    .top
    {
        width: 100%;
        text-align: center;
    }
    #chat_friend_name{
        width: 100%;
        text-align: center;
        font-size: 18px;
    }
    .left{
        user-select: none;
    }
    .chat{
        position: fixed;
        z-index: 100;
        top:100px;
        left: 1200px;
        transition: 0.5s;
        left: -2000px;
    }

    #remind{
        width: 80px;
        height: 25px;
        line-height: 25px;
        background-color: #F56C6C;
        text-align: center;
        color: #fff;
        display: none;
        border-radius: 10px;

    }

    @import "../../assets/css/chat-style.css";
    html,
    body,
    div,
    span,
    applet,
    object,
    iframe,
    h1,
    h2,
    h3,
    h4,
    h5,
    h6,
    p,
    blockquote,
    pre,
    a,
    abbr,
    acronym,
    address,
    big,
    cite,
    code,
    del,
    dfn,
    em,
    img,
    ins,
    kbd,
    q,
    s,
    samp,
    small,
    strike,
    strong,
    sub,
    sup,
    tt,
    var,
    b,
    u,
    i,
    center,
    dl,
    dt,
    dd,
    ol,
    ul,
    li,
    fieldset,
    form,
    label,
    legend,
    table,
    caption,
    tbody,
    tfoot,
    thead,
    tr,
    th,
    td,
    article,
    aside,
    canvas,
    details,
    embed,
    figure,
    figcaption,
    footer,
    header,
    hgroup,
    menu,
    nav,
    output,
    ruby,
    section,
    summary,
    time,
    mark,
    audio,
    video {
        margin: 0;
        padding: 0;
        border: 0;
        font-size: 100%;
        font: inherit;
        vertical-align: baseline;
    }
    article,
    aside,
    details,
    figcaption,
    figure,
    footer,
    header,
    hgroup,
    menu,
    nav,
    section {
        display: block;
    }
    body {
        line-height: 1;
    }
    ol,
    ul {
        list-style: none;
    }
    blockquote,
    q {
        quotes: none;
    }
    blockquote:before,
    blockquote:after,
    q:before,
    q:after {
        content: "";
        content: none;
    }
    table {
        border-collapse: collapse;
        border-spacing: 0;
    }
    .weidu{
        display: inline-block;
        width: 30px !important;
        height: 20px;
        background-color: red !important;
        color: #fff !important;
        text-align: center;
        border-radius: 10px;
        position: absolute;
        display: none;
    }
    ::-webkit-scrollbar {
        width:5px;

    }

    /* 滚动槽 */
    ::-webkit-scrollbar-track {
        border-radius:5px;
    }

    /* 滚动条滑块 */
    ::-webkit-scrollbar-thumb {
        border-radius:10px;
        background: #e8eaf1;
    }

</style>